<?php
/**
 * Created by PhpStorm.
 * User: sunshubo
 * Date: 2017/12/27
 * Time: 13:19
 */

class SendTemplateMsg_control extends MY_Controller
{
    function index()
    {
        $body = $this->input->raw_input_stream;
        $body = json_decode($body);
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $body->t;
        $tempId = 'PvbsxeCyZCPn14FfwHcZ76062MGdg8teTcav_g6iDIM';
        $openid = $body->oid;
        $formId = $body->i;
        $active_date = '2017-12-31';
        $active_addr = "";
        $active_name = "";
        $active_phone = "";
        $remark = "";

        $data = array(
            "touser" => $openid,
            "template_id" => $tempId,
            "page" => "pages/index/index",
            "form_id" => $formId,
            "data" => array(
                "keyword1" => array(
                    "value" => "报名成功",
                    "color" => "#173177"
                ),
                "keyword2" => array(
                    "value" => $active_date,
                    "color" => "#173177"
                ),
                "keyword3" => array(
                    "value" => $active_addr,
                    "color" => "#173177"
                ),
                "keyword4" => array(
                    "value" => $active_name,
                    "color" => "#173177"
                ),
                "keyword5" => array(
                    "value" => $active_phone,
                    "color" => "#173177"
                ),
                "keyword6" => array(
                    "value" => $remark,
                    "color" => "#173177"
                )
            ),
            "emphasis_keyword" => "339208499"
        );

        $res = $this->send_post($url, $data);
        echo($res);
    }

    /**
     * 发送post请求
     * @param string $url 请求地址
     * @param array $post_data post键值对数据
     * @return string
     */
    function send_post($url, $post_data)
    {

//        $postdata = http_build_query($post_data);
        $postdata = json_encode($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        return $result;
    }
}